<template>
  <div class="app-container">
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">绑定商品类别列表</span>
          <div class="right-toolbar">
            <el-form :model="queryParams" ref="queryForm" inline class="search-form">
              <el-form-item label="商品名称" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入商品名称"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="SKU" prop="sku">
                <el-input v-model="queryParams.sku" placeholder="请输入SKU" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          border
          stripe
          highlight-current-row
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column
            prop="id"
            label="ID"
            width="80"
            align="center"
          />
          <el-table-column
            prop="name"
            label="商品名称"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sku"
            label="SKU"
            width="100"
            align="center"
            >
          </el-table-column>
          <el-table-column
            prop="price"
            label="价格"
            width="100"
            align="center"
          >
            <template #default="scope">
              <span class="price-tag">¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="channel"
            label="渠道"
            width="100"
            align="center"
          />
          <el-table-column
            prop="link"
            label="链接"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-link type="primary" :href="scope.row.link" target="_blank" :underline="false">查看链接</el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="image"
            label="图片"
            width="120"
            align="center"
          >
            <template #default="scope">
              <ImagePreview
                v-if="scope.row.image"
                :src="scope.row.image"
                :width="60"
                :height="60"
                fit="cover"
                :lazy="true"
                class="table-image-preview"
              />
              <div v-else class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="itemId"
            label="商品ID"
            width="120"
            align="center"
            show-overflow-tooltip
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="180"
            align="center"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="handleView(scope.row)"
                class="action-button"
              >查看类别</el-button>
              <el-button
                link
                type="primary"
                @click="handleEdit(scope.row)"
                class="action-button"
              >添加类别</el-button>
             
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination
          class="pagination"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>

    <!-- 添加商品类别对话框 -->
    <el-dialog
      :title="productInfo.name ? `${title} - ${productInfo.name}` : title"
      v-model="open"
      width="550px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      class="category-dialog"
    >
      <div class="product-info maginbotton30" v-if="productInfo.id">
        <div class="product-header">
          <div class="product-image-container">
            <el-image
              v-if="productInfo.image"
              :src="productInfo.image"
              fit="cover"
              class="product-image-preview"
            >
              <template #error>
                <div class="image-placeholder-small">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="image-placeholder-small">
              <el-icon><Picture /></el-icon>
            </div>
          </div>
          <div class="product-details">
            <h3 class="product-name">{{ productInfo.name }}</h3>
            <p class="product-price">¥{{ productInfo.price }}</p>
          </div>
        </div>
      </div>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="category-form"
      >

        <el-form-item label="年龄标签" prop="ageTags">
          <el-select
            v-model="form.ageTags"
            multiple
            placeholder="请选择年龄标签"
            style="width: 100%"
            :disabled="viewMode"
          >
            <el-option label="0-12岁" value="age_0_12" />
            <el-option label="12-18岁" value="age_12_18" />
            <el-option label="18-35岁" value="age_18_35" />
            <el-option label="35-45岁" value="age_35_45" />
            <el-option label="45-60岁" value="age_45_60" />
            <el-option label="60岁以上" value="age_60_plus" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别标签" prop="genderTags">
          <el-select
            v-model="form.genderTags"
            multiple
            placeholder="请选择性别标签"
            style="width: 100%"
            :disabled="viewMode"
          >
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
          </el-select>
        </el-form-item>
        <el-form-item label="场合标签" prop="occasionTags">
          <el-select
            v-model="form.occasionTags"
            multiple
            placeholder="请选择场合标签"
            style="width: 100%"
            :disabled="viewMode"
          >
            <el-option label="传统节日" value="traditional_festival" />
            <el-option label="生日" value="birthday" />
            <el-option label="纪念日" value="anniversary" />
            <el-option label="毕业" value="graduation" />
            <el-option label="乔迁" value="moving" />
            <el-option label="平日" value="everyday_gift" />
            <el-option label="父/母亲节" value="fm_festival" />
            <el-option label="儿童节" value="children_day" />
            <el-option label="纪念场合" value="com_occasions" />
            <el-option label="商务" value="business" />
          </el-select>
        </el-form-item>
        <el-form-item label="关系标签" prop="relationshipTags">
          <el-select
            v-model="form.relationshipTags"
            multiple
            placeholder="请选择关系标签"
            style="width: 100%"
            :disabled="viewMode"
          >
            <el-option label="爱人" value="lover" />
            <el-option label="长辈" value="elder" />
            <el-option label="儿童" value="children" />
            <el-option label="亲戚" value="relative" />
            <el-option label="朋友" value="friend" />
            <el-option label="同事" value="colleague" />
            <el-option label="客户" value="client" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型标签" prop="typeTags">
          <el-select
            v-model="form.typeTags"
            multiple
            placeholder="请选择类型标签"
            style="width: 100%"
            :disabled="viewMode"
          >
            <el-option label="饰品" value="jewelry" />
            <el-option label="生活" value="life" />
            <el-option label="美妆护肤" value="skincare" />
            <el-option label="美食" value="food" />
            <el-option label="健康" value="health" />
            <el-option label="文艺" value="art" />
            <el-option label="趣味" value="fun" />
            <el-option label="告白" value="confession" />
            <el-option label="日常(小心意)" value="daily_gift" />
            <el-option label="数码" value="digital" />
            <el-option label="型男必备" value="men_essentials" />
            <el-option label="精选礼盒" value="gift_box" />
            <el-option label="摆件" value="ornament" />
            <el-option label="茶酒" value="tea_wine" />
            <el-option label="定制礼品" value="custom_gift" />
            <el-option label="情侣款" value="couple" />
            <el-option label="玩具" value="toy" />
            <el-option label="图书绘本" value="book" />
            <el-option label="科学益智" value="science_puzzle" />
            <el-option label="玩偶" value="doll" />
            <el-option label="爸爸的礼物精选" value="dad_gift" />
            <el-option label="妈妈的礼物精选" value="mom_gift" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品信息">
          <div class="product-info">
            <div class="product-name">{{ productInfo.name }}</div>
            <div class="product-price">价格: ¥{{ productInfo.price }}</div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <template v-if="viewMode">
            <el-button @click="cancel">关 闭</el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listProducts, getProduct } from '@/api/product/index'
import { uploadCategory, delProductCategory, getCategoryDetail } from '@/api/introduce/category'
import { Picture } from '@element-plus/icons-vue'
import ImagePreview from '@/components/ImagePreview/index.vue'


// 遮罩层
const loading = ref(false)
// 提交按钮加载状态
const submitLoading = ref(false)
// 总条数
const total = ref(0)
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 是否只读模式（查看）
const viewMode = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 表单ref
const formRef = ref()
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: ''
})

// 表单参数
const form = reactive({
  // name: '',
  // description: '',
  // sort: 0,
  productId: undefined,
  ageTags: [],
  genderTags: [],
  occasionTags: [],
  relationshipTags: [],
  typeTags: []
})

// 商品信息
const productInfo = reactive({
  id: undefined,
  name: '',
  price: '',
  image: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '类别名称不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '类别名称长度必须在2到50个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '类别描述长度不能超过500个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '排序不能为空', trigger: 'blur' }
  ]
}

// 表格数据
const tableData = ref([])

/** 查询列表 */
function getList() {
  loading.value = true
  listProducts(queryParams).then(response => {
    tableData.value = response.data.list
    total.value = response.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  // form.name = ''
  // form.description = ''
  // form.sort = 0
  form.productId = undefined
  form.ageTags = []
  form.genderTags = []
  form.occasionTags = []
  form.relationshipTags = []
  form.typeTags = []
  
  productInfo.id = undefined
  productInfo.name = ''
  productInfo.price = ''
  productInfo.image = ''
  
  viewMode.value = false
}

/** 查看按钮操作 */
function handleView(row) {
  reset()
  const id = row.id || row
  
  // 获取商品信息
  getProduct(id).then(response => {
    const product = response.data
    // 保存商品信息到productInfo
    productInfo.id = product.id
    productInfo.name = product.name
    productInfo.price = product.price
    productInfo.image = product.image
    
    // 设置表单中的productId
    form.productId = product.id
    
    // 获取类别详情
    getCategoryDetail(id).then(res => {
      if (res.code === '00000') {
        const data = res.data || {}
        // 填充表单数据
        form.ageTags = Array.isArray(data.ageTags) ? data.ageTags : []
        form.genderTags = Array.isArray(data.genderTags) ? data.genderTags : []
        form.occasionTags = Array.isArray(data.occasionTags) ? data.occasionTags : []
        form.relationshipTags = Array.isArray(data.relationshipTags) ? data.relationshipTags : []
        form.typeTags = Array.isArray(data.typeTags) ? data.typeTags : []
        
        // 设置为查看模式
        viewMode.value = true
        open.value = true
        title.value = '查看商品类别'
      } else {
        ElMessage.error(res.msg || '获取商品类别详情失败')
      }
    }).catch(() => {
      ElMessage.error('获取商品类别详情失败')
    })
  })
}

/** 修改按钮操作 */
function handleEdit(row) {
  reset()
  const id = row.id || row
  getProduct(id).then(response => {
    const product = response.data
    // 保存商品信息到productInfo
    productInfo.id = product.id
    productInfo.name = product.name
    productInfo.price = product.price
    productInfo.image = product.image
    
    // 设置表单中的productId
    form.productId = product.id
    
    // 获取类别详情
    getCategoryDetail(id).then(res => {
      if (res.code === '00000') {
        const data = res.data || {}
        // 填充表单数据
        form.ageTags = Array.isArray(data.ageTags) ? data.ageTags : []
        form.genderTags = Array.isArray(data.genderTags) ? data.genderTags : []
        form.occasionTags = Array.isArray(data.occasionTags) ? data.occasionTags : []
        form.relationshipTags = Array.isArray(data.relationshipTags) ? data.relationshipTags : []
        form.typeTags = Array.isArray(data.typeTags) ? data.typeTags : []
      }
      
      open.value = true
      title.value = '添加商品类别'
    }).catch(() => {
      // 即使获取详情失败，仍然打开对话框让用户添加类别
      open.value = true
      title.value = '添加商品类别'
    })
  })
}

/** 提交按钮 */
function submitForm() {
  // 如果是查看模式，直接关闭对话框
  if (viewMode.value) {
    open.value = false
    return
  }
  
  formRef.value?.validate((valid) => {
    if (valid) {
      // 创建 FormData 对象
      const formData = new FormData();
      // formData.append('name', form.name);
      // formData.append('description', form.description);
      // formData.append('sort', form.sort);
      
      // 确保productId被正确添加
      if (form.productId) {
        formData.append('id', form.productId);
      } else if (productInfo.id) {
        formData.append('id', productInfo.id);
      }
      
      // 添加标签数据 - 使用JSON.stringify将数组转换为字符串
      if (form.ageTags.length > 0) {
        formData.append('ageTags', form.ageTags.join(','));
      }
      
      if (form.genderTags.length > 0) {
        formData.append('genderTags', form.genderTags.join(','));
      }
      
      if (form.occasionTags.length > 0) {
        formData.append('occasionTags', form.occasionTags.join(','));
      }
      
      if (form.relationshipTags.length > 0) {
        formData.append('relationshipTags', form.relationshipTags.join(','));
      }
      
      if (form.typeTags.length > 0) {
        formData.append('typeTags', form.typeTags.join(','));
      }
      
      submitLoading.value = true
      
      // 获取商品ID，确保它被正确传递
      const productId = form.productId || productInfo.id;
      
      if (!productId) {
        ElMessage.error('商品ID不能为空');
        submitLoading.value = false;
        return;
      }
      
      uploadCategory(productId, formData).then(() => {
        ElMessage.success('添加商品类别成功')
        open.value = false
        getList()
      }).catch(() => {
        ElMessage.error('添加商品类别失败')
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idsToDelete = row.id || ids.value
  
  ElMessageBox.confirm(`是否确认删除商品类别编号为"${idsToDelete}"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    return delProductCategory(idsToDelete)
  }).then(() => {
    getList()
    ElMessage.success('删除成功')
  }).catch(error => {
    console.log(error)
    ElMessage.error('删除失败')
  }).finally(() => {
    loading.value = false
  })
}

/** 选择条目触发事件 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 分页大小改变 */
function handleSizeChange(val) {
  queryParams.pageSize = val
  getList()
}

/** 分页页码改变 */
function handleCurrentChange(val) {
  queryParams.pageNum = val
  getList()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.name = ''
  queryParams.sku = ''
  handleQuery()
}

// 初始化数据
getList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.maginbotton30{
  margin-bottom: 30px;
}
.card-title {
  font-size: 18px;
  font-weight: bold;
}

.right-toolbar {
  display: flex;
  align-items: center;
}

.search-form {
  display: flex;
  align-items: center;
}

.table-container {
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-image-preview {
  margin: 0 auto;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
}

.image-placeholder {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}

.price-tag {
  color: #f56c6c;
  font-weight: bold;
}

.action-button {
  margin: 0 5px;
}

.product-info {
  padding: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-price {
  color: #f56c6c;
}

.category-dialog .el-dialog__body {
  padding-top: 10px;
}

.category-form .el-form-item:last-child {
  margin-bottom: 0;
}

.product-header {
  display: flex;
  align-items: center;
  padding: 10px;
}

.product-image-container {
  width: 60px;
  height: 60px;
  margin-right: 10px;
}

.product-image-preview {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.image-placeholder-small {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
}

.product-price {
  color: #f56c6c;
}
</style>
